package ar.edu.itba.pod.Legajo47342;

import java.net.ConnectException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.rmi.RemoteException;

import ar.edu.itba.pod.simul.ObjectFactoryAlternative;
import ar.edu.itba.pod.simul.communication.ConnectionManager;
import ar.edu.itba.pod.simul.market.MarketManager;
import ar.edu.itba.pod.simul.simulation.SimulationManager;

public class ObjectFactoryAlternativeImpl implements ObjectFactoryAlternative {

	private String hostIp;
	private Node node;
	
	public ObjectFactoryAlternativeImpl() {
		super();
		
		try {
			InetAddress address = InetAddress.getLocalHost();
			hostIp = address.getHostAddress();
			if(address.isLoopbackAddress()){
				//workaround para linux machines que devuelven loopback en localhost
				InetAddress[] addresses = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());
				for (InetAddress a : addresses) {
					if(!a.isLoopbackAddress()){
						hostIp = a.getHostAddress();
					}
				}
			}
			System.out.println(hostIp);
			
			node = new Node(hostIp);
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}

	@Override
	public void createGroup() throws ConnectException {
		ConnectionManager manager = node.getManager();
		
		try {
			manager.getClusterAdmimnistration().createGroup();
			System.out.println("Created: "+
					manager.getClusterAdmimnistration().getGroupId());
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	public void connectToGroup(String entryPointId) throws ConnectException {
		ConnectionManager manager = node.getManager();
		
		try {
			manager.getClusterAdmimnistration().connectToGroup(entryPointId);
			
		} catch (RemoteException e) {
			e.printStackTrace();
			throw new ConnectException("Could not connect to cluster at: "+entryPointId);
		}

	}

	@Override
	public ConnectionManager getConnectionManager() {
		return node.getManager();
	}

	@Override
	public MarketManager getMarketManager() {
		return node.getMarketManager();
	}

	@Override
	public SimulationManager getSimulationManager() {
		return node.getSimulManager();
	}

	@Override
	public void disconnect() {
		ConnectionManager manager = node.getManager();
		
		try {
			manager.getClusterAdmimnistration().disconnectFromGroup(node.getNodeId());
			
			node.getClusterNodes().clear();
			node.getLoads().clear();
			node.getAgents().clear();
			
		} catch (RemoteException e) {
			e.printStackTrace();
		}

	}

}
